package viroyal.com.base.model;

import android.content.Context;

import com.suntiago.baseui.utils.SPUtils;
import com.suntiago.network.network.BaseRspObserver;
import com.viroyal.monitorlib.utils.MD5Util;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import viroyal.com.base.AppConfig;
import viroyal.com.base.BuildConfig;
import viroyal.com.base.activity.splash.SplashIp;
import viroyal.com.base.net.ApiObserver;
import viroyal.com.base.net.PhpApi;
import viroyal.com.base.net.entity.IOTMessage;
import viroyal.com.base.net.req.TokenRequest;
import viroyal.com.base.net.rsp.NoticeResponse;
import viroyal.com.base.net.rsp.TokenResponseS;

public class IOTModel {

    private static IOTModel sIOTModel;
    private Context mContext;

    public static IOTModel get() {
        if (sIOTModel == null) {
            sIOTModel = new IOTModel();
        }
        return sIOTModel;
    }


    //初始化
    public static void init(Context context) {
        get().mContext = context;
    }

    /**
     * 获取物联网token
     * @param action1
     */
    public void getToken(Action1<TokenResponseS> action1) {
        String school_id = SPUtils.getInstance(mContext).get(AppConfig.SCHOOL_ID, "1000");
        long time = System.currentTimeMillis() / 1000;
        String password = MD5Util.md5Decode(school_id + "-|-" + AppConfig.KEY + "-|-" + System.currentTimeMillis() / 1000 + "-|-" + AppConfig.SECRET);
        TokenRequest tokenRequest=new TokenRequest(school_id, time, password);
        PhpApi.get().getPhpApi(ApiObserver.class, BuildConfig.IOT_HOST)
                .getToken(tokenRequest)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseRspObserver<>(TokenResponseS.class, action1));
    }

    /**
     * 获取物联网信息
     * @param action1
     * @param msg_type 消息类型 1-轮播 2-广告 不传就是通知公告
     */
    public void getNoice(Action1<NoticeResponse> action1,String msg_type) {
        String school_id = SPUtils.getInstance(mContext).get(AppConfig.SCHOOL_ID, "1000");
        String token = SPUtils.getInstance(mContext).get(AppConfig.ACCESS_TOKEN, "");
        String device_id = SPUtils.getInstance(mContext).get(AppConfig.DEVICE_ID, "");
        PhpApi.get().getPhpApi(ApiObserver.class, BuildConfig.IOT_HOST)
                .getNoice("Bearer " + token, school_id, new IOTMessage(device_id, "1.0", msg_type))
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseRspObserver<>(NoticeResponse.class, action1));
    }
}
